package com.lemon.cloud.websocket.interceptor;

import cn.hutool.core.util.StrUtil;
import com.lemon.cloud.websocket.holder.SessionKeyGenerator;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * 拦截器，获取USER_KEY_ATTR_NAME
 *
 * @author HuangDS
 */
public class SessionKeyInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response,
                                   WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) {
        String accessToken = ((ServletServerHttpRequest) request).getServletRequest().getParameter("access_token");
        if (StrUtil.isNotEmpty(accessToken)) {
            attributes.put(SessionKeyGenerator.USER_KEY_ATTR_NAME, accessToken);
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
    }


}
